<template>
	<view class="search">
		<Lines />

		<view class="search-item">
			<view class="search-title">
				<view class="f-color">最近搜索</view>
				<view class="iconfont icon-iconset0213" @tap="clearHistory"></view>
			</view>
			<view v-if="searchData.length > 0">
				<view class="search-name f-color" v-for="(item,index) in searchData" :key="index">{{item}}</view>

			</view>
			<view v-else class="search-end">暂无搜索数据</view>
		</view>
		<view class="search-item">
			<view>
				<view class="f-color">热门搜索</view>
			</view>
			<view>
				<view class="search-name f-color">四件套</view>
				<view class="search-name f-color">面膜</view>
			</view>
		</view>
	</view>
</template>

<script>
	import Lines from '@/components/common/Line.vue'
	export default {
		data() {
			return {
				//输入的关键词
				keyword: '',
				//搜索过的词记录
				searchData: []

			}
		},
		//页面加载的时候
		onLoad() {
			uni.getStorage({
				key:"searchData",
				success: (res) => {
					// console.log(res)
					this.searchData = JSON.parse(res.data)
				}
			})
		},
		// 标题栏点击事件
		onNavigationBarButtonTap(e) {
			this.search()
		},
		//点击顶栏中的搜索按钮
		onNavigationBarSearchInputChanged(e) {
			this.keyword = e.text
		},
		components: {
			Lines
		},
		methods: {
			//判断关键词是否为空和跳转页面
			search() {
				if (this.keyword === "") {
					return uni.showToast({
						title: "关键词不允许为空",
						// 图标
						icon: "none"
					})
				} else {
					//跳转路径
					uni.navigateTo({
						url: "/pages/search-list/search-list?keyword="+this.keyword+""
					})
				}
				// 隐藏软键盘
				uni.hideKeyboard();
				this.addSearch();
			},
			//记录最近搜索词
			addSearch() {
				//this.searchData.indexOf(this.keyword) 判断里面有没有搜索词
				let idx = this.searchData.indexOf(this.keyword)

				if (idx < 0) {
					this.searchData.unshift(this.keyword)
				} else {
					this.searchData.unshift(this.searchData.splice(idx, 1)[0]);
				}
				uni.setStorage({
					key:"searchData",
					data:JSON.stringify(this.searchData)
				})
			},
			//清除搜索记录
			clearHistory(){
				// 模态框
				uni.showModal({
					title:"重要提示",
					content:"是否要清除搜索记录",
					cancelText:"取消",
					confirmText:"确定",
					success: (res) => {
						// console.log(res)
						if(res.confirm){
							//清除数据存储
							uni.removeStorage({
								key:"searchData"
							})
							//更新视图层
							this.searchData=[]
						}
					}
				})
			}
		},
	}
</script>

<style scoped>
	.search-item {
		padding: 20rpx;
	}

	.search-title {
		display: flex;
		justify-content: space-between;
	}

	.search-name {
		padding: 4rpx 24rpx;
		background-color: #E1E1E1;
		display: inline-block;
		border-radius: 26rpx;
		margin: 10rpx;
	}

	.search-end {
		text-align: center;
	}
</style>
